package com.piece.core.web.util;

import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.JsonUtil;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * 网页返回流工具
 */
public class ResponseUtil {

    private ResponseUtil() {
        throw new IllegalStateException("对象禁止实例化");
    }

    /**
     * 通过流写到前端
     *
     * @param response
     * @param msg        返回信息
     * @param httpStatus 返回状态码
     */
    public static void responseWriter(HttpServletResponse response, String msg, int httpStatus) throws IOException {
        AjaxResponse result = new AjaxResponse(httpStatus, msg);
        responseWrite(response, result);
    }

    /**
     * 通过流写到前端
     *
     * @param response
     * @param obj
     */
    public static void responseSucceed(HttpServletResponse response, Object obj) throws IOException {
        AjaxResponse result = AjaxResponse.success(I18nUtil.message(ExceptionConstants.MESSAGE_SUCCESS), obj);
        responseWrite(response, result);
    }

    /**
     * 通过流写到前端
     *
     * @param response
     * @param msg
     */
    public static void responseFailed(HttpServletResponse response, String msg) throws IOException {
        AjaxResponse result = AjaxResponse.error(msg);
        responseWrite(response, result);
    }

    /**
     * 通过流写到前端
     *
     * @param response
     * @param msg
     */
    public static void responsePermitted(HttpServletResponse response, String msg) throws IOException {
        AjaxResponse result = AjaxResponse.error(I18nUtil.message(ExceptionConstants.PERMISSION), msg);
        responseWrite(response, result);
    }

    private static void responseWrite(HttpServletResponse response, AjaxResponse result) throws IOException {
        response.addHeader("Cache-Control", "no-store");
        response.addHeader("Pragma", "no-cache");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        try (Writer writer = response.getWriter()) {
            writer.write(JsonUtil.toJson(result));
            writer.flush();
        }
    }
}
